#获取音乐小案例
from urllib.parse import unquote,quote
from fake_useragent import UserAgent
import requests
import random
# url ="https://lx-sycdn.kuwo.cn/35901fd5ccb95c5e497664769bc744ba/686817dd/resource/n2/1/85/2962310159.mp3?bitrate$128&from=vip"
# headers = {"User-Agent":UserAgent().random}
# res = requests.get(url,headers=headers)
# print(res.request.headers)
# with open(r"C:\Users\a2038\Desktop\爬虫文件夹\音乐\test.mp3","wb") as f:
#     f.write(res.content)
#改写为面向对象
class Music(object):
    """爬取音乐"""
    def __init__(self,url,headers):
        self.url = url
        self.headers = headers
    #发送请求,并返回响应
    def gets(self):
        res = requests.get(self.url, headers=self.headers)
        return res
    #保存数据
    @staticmethod
    def saves(url,mode,res):
        with open(url, mode) as f:
            f.write(res.content)
    #运行
    def run(self,url,mode):
        self.saves(url,mode, self.gets())
#参数数据
url ="https://lx-sycdn.kuwo.cn/35901fd5ccb95c5e497664769bc744ba/686817dd/resource/n2/1/85/2962310159.mp3?bitrate$128&from=vip"
headers = {"User-Agent":UserAgent().random}
#使用对象来执行
music = Music(url,headers)
music.run(r"C:\Users\a2038\Desktop\爬虫文件夹\音乐\test3.mp3","wb") #能够正常使用
